﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChampionFramework.Models;

namespace ChampionFramework.Controllers
{
    public class GruposController : Controller
    {
        private ChampionContextContainer db = new ChampionContextContainer();

        public ActionResult Details(int id = 0)
        {
            Grupo grupo = db.GrupoSet.Include("Time").Single(g => g.Id == id);
            if (grupo == null)
            {
                return HttpNotFound();
            }
            return View(grupo);
        }

        public ActionResult AddTime(int id = 0)
        {
            Grupo grupo = db.GrupoSet.Single(g => g.Id == id);
            if (grupo == null)
            {
                return HttpNotFound();
            }
            ViewBag.TimeId = new SelectList(db.TimeSet, "Id", "Nome");
            return View(grupo);
        }

        [HttpPost]
        public ActionResult AddTime(Grupo grupo)
        {
            if (ModelState.IsValid)
            {
                int timeId = Convert.ToInt32(Request.Params["TimeId"]);
                Time time = db.TimeSet.Single(t => t.Id == timeId);
                grupo.Time.Add(time);
                db.ObjectStateManager.ChangeObjectState(grupo, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = grupo.Id });
            }
            ViewBag.TimeId = new SelectList(db.TimeSet, "Id", "Nome");
            return View(grupo);
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}